/**
 * 
 */
package org.xserver.runtime.jetty.command;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

/**
 * @author jkonopka
 * 
 */
public class MergeSettingsCommand extends AbstractSettingsInitializeCommand {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3863882994919700554L;

	/**
	 * 
	 */
	private static final String STAGE = "stage";

	/**
	 * 
	 */
	private static final String SERVER_STAGE = "server.stage";

	/**
	 * 
	 */
	private static final String VERSION = "server.version";

	/**
	 * @param properties {@link Properties}
	 */
	public MergeSettingsCommand(final Properties properties) {
		super(properties);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.xserver.core.command.ICommand#execute()
	 */
	@Override
	public void execute() throws Exception {
		getProperties().putAll(getSettings());
		getProperties().put(VERSION, getBundle().getString(VERSION));
		System.setProperty(STAGE, getProperties().getProperty(SERVER_STAGE));
	}

	/**
	 * @return {@link Properties} from user settings file
	 * @throws Exception error handling
	 */
	public synchronized Properties getSettings() throws Exception {
		final Properties properties = new Properties();
		final File file = getUserSettingsFile();
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			properties.loadFromXML(in);
		} catch (final Exception e) {
			getLog().warn(
					String.format("Die Datei '%s' mit den Einstellungen konnten nicht geladen werden.",
							file.getAbsolutePath()));
		} finally {
			IOUtils.closeQuietly(in);
		}
		return properties;
	}

}
